var http = require("http");
var express = require("express");
var RED = require("node-red");
var config = require("./settings");

// Create an Express app
var app = express();
const cors = require("cors"); // 引入cors模块

app.use(cors()); // 这允许所有来源的跨域请求，根据实际情况调整选项
app.use(express.json()); // 用于解析JSON格式的请求体

// Add a simple route for static content served from 'public'
app.use("/", express.static("public"));

// Create a server
var server = http.createServer(app);

// Create the settings object - see default settings.js file for other options
var settings = {
  ...config,
  // nodered访问前缀
  httpAdminRoot: "/red",
  // api访问前缀
  httpNodeRoot: "/api",
  userDir: __dirname + "/flowData",
  functionGlobalContext: {}, // enables global context
};

// Initialise the runtime with a server and settings
RED.init(server, settings);

// Serve the editor UI from /red
app.use(settings.httpAdminRoot, RED.httpAdmin);

// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot, RED.httpNode);

app.get("/api/data", (req, res) => {
  console.log(req.query, "req.query");
  console.log(req.body, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: {
      value: req.query.name,
    },
  });
});

app.post("/api/updateData", (req, res) => {
  console.log(req.body, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: req.body.name + "这是post请求的",
  });
});

app.post("/deploy", (req, res) => {
  console.log(req.body, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: req.body.data.value + "这是post请求的",
  });
});

app.post("/get/data", (req, res) => {
  console.log(req.body, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: {
      value: new Date().getTime().toString(),
    },
  });
});

app.get("/get/data", (req, res) => {
  console.log(req.query, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: {
      value: req.query.name
        ? `传过来的是这个=>${JSON.stringify(req.query) || ""}`
        : "没有值传过来",
    },
  });
});

app.post("/get/getParams", (req, res) => {
  console.log(req.body, "req.body");
  res.send({
    code: "success",
    msg: "成功",
    data: {
      value: req.body.name
        ? `传过来的是这个=>${JSON.stringify(req.body) || ""}`
        : "没有值传过来",
      params: JSON.stringify(req.body),
    },
  });
});

server.listen(1880);

// Start the runtime
RED.start().then(() => {
  console.log("已经启动nodered了");
});
